import classNames from 'classnames'
import { useEffect, useRef, useState } from 'react'
import { useDispatch } from 'react-redux'
import { del, updateState } from '../store/actions/todos'
export default function TodoItem({ item }) {
  const dispatch = useDispatch()
  // 双击任务获取当前任务的数据
  const [current, setCurrent] = useState({
    id: '',
    name: '',
  })
  // 双击显示输入框ref
  const inputRef = useRef(null)

  // 双击显示输入框自动获取焦点
  useEffect(() => {
    inputRef.current.focus()
  }, [current])

  // 回车修改
  const onKeyUp = (e) => {
    // enter
    if (e.keyCode === 13) {
      dispatch(
        updateState(item.id, {
          id: item.id,
          name: current.name,
          isDone: item.isDone,
        })
      )
      setCurrent({ id: '', name: '' })
    }
    // esc
    if (e.keyCode === 27) {
      setCurrent({ id: '', name: '' })
    }
  }

  // 删除
  const delList = (id) => {
    dispatch(del(id))
  }
  // 修改任务完成状态
  const onChange = (item) => {
    const data = {
      id: item.id,
      name: item.name,
      isDone: !item.isDone,
    }
    dispatch(updateState(item.id, data))
  }

  return (
    <li
      className={classNames({
        completed: item.isDone,
        editing: item.id === current.id,
      })}
    >
      <div className="view">
        <input
          className="toggle"
          type="checkbox"
          checked={item.isDone}
          onChange={() => {
            onChange(item)
          }}
        />
        <label
          onDoubleClick={() => {
            setCurrent({ id: item.id, name: item.name })
          }}
        >
          {item.name}
        </label>
        <button
          className="destroy"
          onClick={() => {
            delList(item.id)
          }}
        />
      </div>
      <input
        className="edit"
        ref={inputRef}
        value={current.name}
        // value={item.name}
        onChange={(e) => setCurrent({ id: item.id, name: e.target.value })}
        onBlur={() => setCurrent({ id: '', name: '' })}
        onKeyUp={onKeyUp}
      />
    </li>
  )
}
